// 获取搜索提交按钮按钮
let sumbitSearchBtn = document.getElementById("submitSearchBtn");

// 获得放入搜索结果的容器
let searchResultBox = document.getElementById("searchResultBox");

let Ipt = document.getElementById("searchIpt").value;

let IptPress = document.getElementById("searchIpt");

var searchDy = "";

var searchDyLen = 0;

// 为搜索的时候按回车绑定事件
IptPress.onkeydown = function(){
    let e = window.event;
    var keycode =e.which||e.keyCode;
    if(keycode == 13){
        // 触发搜索提交按钮
        sumbitSearchBtn.click();
    }
}

// 获得插入到html中的封面模板字符串
function htmlDyTopS(data){
    var str = '';
 
        str = ` <div class="everyDyBox">
              <div class="Dycover">
                <h3 class="detailDyS">${data.title}</h3>
                <li class="DyCoverContent">${data.content}</li>
                <ul>
                  <li class="DyCoverName"> ${data.username}</li>
                  <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>  
                </ul>
              </div>        
            </div>
            `;
          return str;
    }
    
// 获得插入到html中的动态详细内容的模板字符串
function htmlDyDetailS(data){
  var str = '';
  var imgStr ='';
  if(data.hasPicture){
      let imgLen = data.urls.length;
      for(let i = 0 ; i<imgLen ; i++){
        imgStr +=`   <li class="DyImgContent"><img style="width: 250px;height: 250px;" src=${queryURL}${data.urls[i]} alt=""></li>`
      }
      str = ` <div class="everyDyBox">
           
            <div class="everyDy">
              <ul class="userDyInfo">
              <li class="userDyTitle">${data.title}</li>

              </ul>
              <ul class="userDyHeader">
                <li class="DyId">动态ID:${data.id}</li>
                <li class="userDyId">用户ID:${data.userId}</li>
                <li class="userDyname">用户名称:${data.username}</li>
                <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>      
              </ul>
              <ul class="userDyContent">
                <ul class="DyimgBox">
                 ${imgStr}
                </ul>
                <li class="DyTextContent">${data.content}</li>
              </ul>
              <li class="backPerAllDy">
              <i class="fas fa-reply"></i> 
              </li>
            </div>
          </div>
          `;
  }
  else{
      str = `   <div class="everyDyBox">
      <div class="everyDy">
        <ul class="userDyInfo">
        <li class="userDyTitle">${data.title}</li>
        </ul>
        <ul class="userDyHeader">
      
          <li class="DyId">动态ID:${data.id}</li>
          <li class="userDyId">用户ID:${data.userId}</li>
          <li class="userDyname">用户名称:${data.username}</li>
          <li class="userDyTime">发布时间:${switchTimeFormat(data.creationTime)}</li>      
        </ul>
        <ul class="userDyContent">
          <li class="DyTextContent">${data.content}</li>
        </ul>
        <li class="backPerAllDy">
        <i class="fas fa-reply"></i> 
        </li>
      </div>
    </div>`;
  }
  return str;
}

// 插入模板字符串操作
function insertSearchHtml(value){
    let dySearchCover = "";
    let len = value.data.length;
    for(let i = 0 ; i < len ; i++ ){
        dySearchCover += htmlDyTopS(value.data[i]);
    }
    searchResultBox.innerHTML = dySearchCover;
    
}


// 评论的模板字符串(内含回复，删除，返回，评论功能)
function commentSearchStr(commentArrays,commentOwner){
 
  let comment = `<div class="CommentsBox">
 <li>评论区</li>
  <textarea
  type="text"
  placeholder="请在此处输入评论内容"
  id="newCommentContent"
  name="content"
  style="resize: none; font-size: 18px"
></textarea>
<button  type="button" class="commentBtn">新增评论</button>
</div>
  `;
  searchResultBox.innerHTML += comment;
  let len = commentArrays.length;
  console.log(commentArrays);
// for遍历所有回复评论到页面种
  for(let k = 0 ; k < len ; k++){
   
    if(commentArrays[k].replyId == 0){

      comment = ` 
          <div class="everyCm"> 
            <li class="mainComment"><img id="replyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].replyerName}" : ${commentArrays[k].commentsContent} 
            <button type="button" id="replyBtn${commentArrays[k].id}">回复</button> 
           `;


          if(window.userInfoG){
            if(commentArrays[k].replyerId == window.userInfoG.data.id){
            
              comment+=`<button id="commentDelBtn${commentArrays[k].id}">删除</button>   
            `
            }
          }
            comment +=`
            </li>
         <div id = "replyBox${commentArrays[k].id}"></div>
          </div>`
          searchResultBox.innerHTML += comment;
     
    }
    else{
      for(let j = 0 ; j < len ; j++){
        if(commentArrays[k].replyId == commentArrays[j].id){
          comment = ` 
          <div class="everyReply"> 
            <li class="mainComment"><img id="replyerAvatar" src="${queryURL}${commentArrays[k].replyerPhoto}" alt="">"${commentArrays[k].replyerName}"回复<img id="replyerAvatar" src="${queryURL}${commentArrays[k].beReplyerPhoto}" alt="">"${commentArrays[k].beReplyerName}"说 : ${commentArrays[k].commentsContent}
            <button type="button" id="replyBtn${commentArrays[k].id}">回复</button> 
            `;

            if(window.userInfoG){
              if(commentArrays[k].replyerId == window.userInfoG.data.id){       
                comment+=`<button id="commentDelBtn${commentArrays[k].id}">删除</button>   
              `
              }
            }
              comment +=`
              </li>
           <div id = "replyBox${commentArrays[k].id}"></div>
            </div>`
          document.getElementById(`replyBox${commentArrays[j].id}`).innerHTML += comment;
        }
      }
     
    }
  }

   // 为返回按钮绑定事件
   let backPerAllBtn = document.querySelector(".backPerAllDy");    
   backPerAllBtn.onclick = function(){
    Ipt = document.getElementById("searchIpt").value;
    if(Ipt){
        let urls = "dynamicState/search/" + Ipt;
        pathGetData(urls).then(
            value=>{
                if(value.code == 200){
                   
                  // 将响应的内容在insert函数中转化并插入到容器中显示
                    insertSearchHtml(value);
                    // 这里相对于查看所有动态是有所优化了,没有使用全局变量
                    let detailBtn = document.getElementsByClassName("detailDyS");
                    // 传入所有动态和动态小卡片上面的标题按钮到函数中进行绑定事件
                    toSearchDetail(value,detailBtn);

                    if(isNight){
                      nightBtn.click();
                    }
                    else{
                      sunBtn.click();
                    }
                }
                else if(value.code == 11000){
                    alert(value.msg);
                }
            },
            reason=>{}
            )
    }
    else{
        alert("请输入搜索内容");
    }
   }
 
  // 为删除回复和添加回复按钮绑定事件
  for(let k = 0 ; k < len ; k++){
    if(window.userInfoG){
      if(commentArrays[k].replyerId == window.userInfoG.data.id){
        let itsId = commentArrays[k].id;
        let ownerId = commentArrays[k].replyerId;
        document.getElementById(`commentDelBtn${itsId}`).onclick = function(){
    //  在自己的动态下可以删除别人的评论
          if(ownerId == window.userInfoG.data.id){
            let data = new FormData();
            data.append("id",itsId)
            postForm(data,"comment/delete").then(value=>{
              if(value.code == 200){
                alert("删除评论成功");
                backPerAllBtn.click();
              }
            });
    
    
          }
          else{
            alert("只能删除自己的评论或者回复哦~");
          }
        
        }


      }

    }
   
    let itsId = commentArrays[k].id;
    let ownerId = commentArrays[k].replyerId;
    document.getElementById(`replyBtn${itsId}`).onclick = function(){
      if(userInfoG){
        let ipt = prompt("请输入你想要回复的内容:","");
        if(ipt){
          let data = new FormData();
   
          data.append("dynamicStateId",commentArrays[0].dynamicStateId);
          data.append("replyId",itsId);
          data.append("replyerId",window.userInfoG.data.id);
          data.append("beReplyerId",ownerId);
          data.append("commentsContent",ipt);
          postForm(data,"comment/reply").then(value=>{
            if(value.code == 200){
              alert(value.msg);
              backPerAllBtn.click();
            }
          },reason=>{
            alert("是否格式不对")
          })
        }
        else{
          alert("内容为空");
        }
      }
      else{
        alert("请先登陆!");
      }
    }

  }


  //  为发表新评论按钮绑定事件
  let newCommentBtn = document.querySelector(".commentBtn");
  newCommentBtn.onclick = function(){
    if(userInfoG){
      let ipt = document.getElementById("newCommentContent").value;
      let data = new FormData();
   
      data.append("dynamicStateId",commentArrays[0].dynamicStateId);
      data.append("replyerId",window.userInfoG.data.id);
      data.append("beReplyerId",commentOwner);
      data.append("commentsContent",ipt);
      if(ipt){
        postForm(data,"comment/insert").then(function(value){
          if(value.code == 200){
            alert("发表评论成功");
            backPerAllBtn.click();
          }
        },function(reason){
          alert("请检查格式!")
        })
      }
      else{
        alert("您暂未输入任何内容!");
      }
    }
    else{
      alert("请先登陆!");
    }
   

  } 
  
}

// 当没有评论时开辟评论区的一个函数
function firstSearchComment(dyId,commentOwner){
  let comment = `<div class="CommentsBox">
  <li>评论区</li>
  <textarea
  type="text"
  placeholder="请在此处输入评论内容"
  id="newCommentContent"
  name="content"
  style="resize: none; font-size: 18px"
></textarea>
  <button  type="button" class="commentBtn">新增评论</button>
  </div>
  `;
  searchResultBox.innerHTML += comment;

   // 为返回按钮绑定事件
   let backPerAllBtn = document.querySelector(".backPerAllDy");    
   backPerAllBtn.onclick = function(){
    Ipt = document.getElementById("searchIpt").value;
    if(Ipt){
        let urls = "dynamicState/search/" + Ipt;
        pathGetData(urls).then(
            value=>{
                if(value.code == 200){
                   
                  // 将响应的内容在insert函数中转化并插入到容器中显示
                    insertSearchHtml(value);
                    // 这里相对于查看所有动态是有所优化了,没有使用全局变量
                    let detailBtn = document.getElementsByClassName("detailDyS");
                    // 传入所有动态和动态小卡片上面的标题按钮到函数中进行绑定事件
                    toSearchDetail(value,detailBtn);

                    if(isNight){
                      nightBtn.click();
                    }
                    else{
                      sunBtn.click();
                    }
                }
                else if(value.code == 11000){
                    alert(value.msg);
                }
            },
            reason=>{}
            )
    }
    else{
        alert("请输入搜索内容");
    }
   }
  //  为发表新评论按钮绑定事件
  let newCommentBtn = document.querySelector(".commentBtn");
  newCommentBtn.onclick = function(){
    if(userInfoG){
    let ipt = document.getElementById("newCommentContent").value;
    let data = new FormData();
      
    data.append("dynamicStateId",dyId);
    data.append("replyerId",window.userInfoG.data.id);
    data.append("beReplyerId",commentOwner);
    data.append("commentsContent",ipt);
      if(ipt){
        postForm(data,"comment/insert").then(function(value){
          if(value.code == 200){
            alert("发表评论成功");
            backPerAllBtn.click();
          }
        },function(reason){
          alert("请检查格式!")
        })
      }
      else{
        alert("您暂未输入任何内容!");
      }
    }
    else{
    alert("请先登陆!");
    }


  } 

}




function getSearchCommentText(dyId,userId){
  
  let data = new FormData();
  data.append("dynamicId",dyId);
  postForm(data,"getReplyById").then(value=>{
    if(value.code == 1000){
 
      
      commentSearchStr(value.data,userId);
    }
    else if(value.code == 1001){
      firstSearchComment(dyId,userId);
    }
  },reason=>{
    alert("发送请求失败，请检查输入格式")
  })


}

// 为动态小卡片标题绑定进入详细动态的事件
function toSearchDetail(value,detailBtn){
  searchDy = value;
  searchDyLen = value.data.length;
    let len = value.data.length;
    for(let i = 0; i < len ; i++){
        detailBtn[i].onclick = function(){
            let str = htmlDyDetailS(value.data[i]);
            searchResultBox.innerHTML = str;

            // 变成详细动态后，对详细里面的回退按钮绑定事件
            //(回退=再次发送AJAX请求所有数据变成动态小卡片再插入)
           
            getSearchCommentText(value.data[i].id,value.data[i].userId);
        }
    }
}

// 委婉的提示
function tipOfSearch(str){
  let content = `<div style="margin:20px auto;" class="tips">
    <li>${str} </li>
  <div>
  `
  searchResultBox.innerHTML = content;
}

sumbitSearchBtn.addEventListener("click",function(){
  // 显示搜索到的内容的盒子 
    searchResultBox.style.display = "flex";

    // 获取输入框的内容
    Ipt = document.getElementById("searchIpt").value;
    if(Ipt){
        let urls = "dynamicState/search/" + Ipt;
        pathGetData(urls).then(
            value=>{
                if(value.code == 200){
                   
                  // 将响应的内容在insert函数中转化并插入到容器中显示
                    insertSearchHtml(value);
                    // 这里相对于查看所有动态是有所优化了,没有使用全局变量
                    let detailBtn = document.getElementsByClassName("detailDyS");
                    // 传入所有动态和动态小卡片上面的标题按钮到函数中进行绑定事件
                    toSearchDetail(value,detailBtn);

                    if(isNight){
                      nightBtn.click();
                    }
                    else{
                      sunBtn.click();
                    }
                }
                else if(value.code == 11000){
                    tipOfSearch(value.msg);
                    document.getElementById("searchIpt").value = "";
                }
            },
            reason=>{}
            )
    }
    else{
        alert("请输入搜索内容");
    }

})


